package com.zzgele.qmzb.api.web;

import com.alibaba.boot.dubbo.annotation.DubboConsumer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.zzgele.qmzb.api.bean.WechatInfoBean;
import com.zzgele.qmzb.api.core.Constants;
import com.zzgele.qmzb.api.core.Result;
import com.zzgele.qmzb.api.core.ResultGenerator;
import com.zzgele.qmzb.api.model.*;
import com.zzgele.qmzb.api.service.*;
import com.zzgele.qmzb.api.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Martin on 2017/07/09.
 */
@RestController
@RequestMapping("/user")
public class UserController {
    private final Logger logger = LoggerFactory.getLogger(UserController.class);
    @DubboConsumer
    private UserService userService;
    @DubboConsumer
    private UserVService userVService;
    @DubboConsumer
    private SmsService smsService;
    @DubboConsumer
    private FansService fansService;
    @DubboConsumer
    private UserAuthenticationService userAuthenticationService;
    @DubboConsumer
    private WechatUserInfoService wechatUserInfoService;
    @DubboConsumer
    private QqUserInfoService qqUserInfoService;
    @DubboConsumer
    private UserLogService userLogService;

    @DubboConsumer
    private WithdrawalsLogService withdrawalsLogService;
    @DubboConsumer
    private RoomService roomService;

    /**
     * 检测短信验证码
     * @param mobile 手机号
     * @param sms_code 验证码
     * @return
     */
    private Result checkSmsCode(String mobile, String sms_code){
        logger.info("checkSmsCode mobile:{} sms_code:{}", mobile ,sms_code);
        if(StringUtils.isBlank(mobile)||StringUtils.isBlank(sms_code)){
            return ResultGenerator.genFailResult("参数检查错误");
        }
        Sms sms = smsService.findBy("mobile", mobile);
        if(sms == null) {
            return ResultGenerator.genFailResult("请先发送验证码");
        }
        Integer current= DateUtil.getCurUnixTimeStampInt();
        Integer old=sms.getCreateTime();
        if((current-old)>60*5){
            return ResultGenerator.genFailResult("请先发送验证码");
        }
        //TODO:检测数据库中的sms_code，并检测发送时间判断是否过期
        if (!sms.getCode().equals(sms_code)) {
            return ResultGenerator.genFailResult("验证码不正确");
        }

        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/login")
    public Result login(String mobile, String sms_code, Integer province_id, Integer city_id, Integer client_type){
        if(StringUtil.isEmpty(mobile) || StringUtil.isEmpty(sms_code)) {
            return ResultGenerator.genFailResult("手机号和验证码均不能为空");
        }
        if(!"11111111111".equals(mobile) &&  !"22222222222".equals(mobile)){
            //检测短信验证码
            Result checkSmsCodeResult = checkSmsCode(mobile, sms_code);
            if (checkSmsCodeResult.getCode() != 200) {
                return checkSmsCodeResult;
            }
        }
        //第一次登录
        Boolean isFirstLogin = false;

        Integer clientType = ClientUtil.getClientType(client_type);

        //检测用户手机号是否已注册
        User user = userService.findBy("mobile", mobile);
        //该手机号未注册
        if (user == null) {
            isFirstLogin = true;

            user = new User();
            user.setMobile(mobile);
            user.setNickName("");
            user.setBirth("");
            user.setProvinceId(province_id);
            user.setCityId(city_id);
            user.setAccountStatus(1);
            user.setAuthenticationStatus(Constants.RZ);
            user.setClientType(Constants.CLIENT_TYPE_UNKNOWN);
            user.setCreateTime(DateUtil.getCurUnixTimeStampInt());
            if(Constants.IS_DEBUG) {
                user.setDiamond(new BigDecimal(0)); //开发调试阶段新用户默认充钻10万
            } else {
                user.setDiamond(new BigDecimal(0));
            }
            user.setDiamondRecharge(new BigDecimal(0));
            user.setIcon("");
            user.setGender(0);
            user.setHeight(0);
            user.setHotDesc(0);
            user.setIdCard("");
            user.setLevel(Constants.USER_LEVEL_DEF);
            user.setPayPass("");
            user.setPid(0);
            user.setUserType(Constants.USER_TYPE_AUDIENCE);
            user.setPraise(0);
            user.setProfit(new BigDecimal(0));
            user.setProfitTotal(new BigDecimal(0));
            user.setPushStatus(Constants.USER_PUSH_STATUS_DEF);
            user.setRealName("");
            user.setRecommendType(Constants.USER_RECOMMEND_TYPE_NO);
            user.setSign("");
            user.setSpend(0);
            user.setTicket(new BigDecimal(0));
            user.setTicketTotal(new BigDecimal(0));
            user.setLastLoginTime(DateUtil.getCurUnixTimeStampInt());
            user.setNumber(0L);
            user.setTotalLoginCount(0);
            user.setTotalOnlineTime(0);
            user.setToken(StringUtil.getLoginToken());
            user.setImAccid("");
            user.setImToken("");
            userService.save(user);

            //logger.info("{}", user);

        } else {
            //TODO:检测已注册用户状态
            if(user.getAccountStatus().equals(0)) {
                return ResultGenerator.genFailResult("帐号已禁用");
            }
            //if(StringUtil.isEmpty(user.getMobile())) {
            //    return ResultGenerator.genFailResult("请绑定手机号");
            //}
        }

        //TODO:提炼成单独方法
        //如果ImAccid或ImToken为空 重新创建IM帐号
        if(StringUtil.isEmpty(user.getImAccid()) || StringUtil.isEmpty(user.getImToken())) {
            //创建网易IM帐号
            String accid = UserUtil.getImAccid();
            //扩展字段
            String props = "";
            //HashMap propsMap = new HashMap();
            //propsMap.put("uid", user.getId());
            //propsMap.put("level", Constants.USER_LEVEL_DEF);
            //props = JSON.toJSONString(propsMap);

            String resIm = NeteaseImUtil.createUser(accid, user.getNickName(), props, user.getIcon());
            try {
                JSONObject jsonObjIm = JSON.parseObject(resIm);
                Integer codeIm = jsonObjIm.getInteger("code");
                if (!codeIm.equals(200)) {
                    String errorDesc = jsonObjIm.getString("desc");
                    logger.warn("IM服务器异常({}):{}", codeIm, errorDesc);
                    return ResultGenerator.genFailResult("IM服务器异常(" + codeIm + "):" + errorDesc);
                }

                JSONObject objectIm = jsonObjIm.getJSONObject("info");

                //保存IM相关信息
                String imAccid = objectIm.getString("accid");
                //String imName = objectIm.getString("name");
                String imToken = objectIm.getString("token");

                user.setImAccid(imAccid);
                user.setImToken(imToken);

                //扩展信息 ===> 改成由客户端去更新扩展信息
                /*
                HashMap extHashMap = new HashMap();
                extHashMap.put("level", user.getLevel());
                String extJsonString = JSONUtils.toJSONString(extHashMap);
                //更新用户IM名片
                resIm = NeteaseImUtil.updateUinfo(user.getImAccid(), user.getNickName(), user.getIcon(), user.getSign(), user.getBirth(), user.getGender(), extJsonString);
                jsonObjIm = JSON.parseObject(resIm);
                codeIm = jsonObjIm.getInteger("code");
                if(!codeIm.equals(200)) {
                    String errorDesc = jsonObjIm.getString("desc");
                    return ResultGenerator.genFailResult("IM服务器异常(" + codeIm + "):" + errorDesc);
                }*/
            } catch (Exception ex) {
                logger.warn("IM服务器异常:{}", ex);
                return ResultGenerator.genFailResult("IM服务器异常:" + ex);
            }
        }

        if(user.getNumber().equals(0L)) {
            //TODO:靓号预生成-取值
            Long max=userService.getMaxNumber();
            user.setNumber(UserUtil.getNumberById(user.getId(),max));
        }
        if(StringUtil.isEmpty(user.getNickName())) {
            //设置临时昵称
            String nickName = UserUtil.getNickNameById(user.getNumber());
            user.setNickName(nickName);
        }

        //更新登录信息
        user.setLastLoginTime(DateUtil.getCurUnixTimeStampInt());
        user.setTotalLoginCount(user.getTotalLoginCount() + 1);
        user.setToken(StringUtil.getLoginToken());

        //更新客户端类型
        user.setClientType(clientType);

        //更新用户信息
        userService.update(user);

        Long userId = user.getId();

        HashMap hashMap = new HashMap();
        hashMap.put("login_uid", userId);
        hashMap.put("login_token", user.getToken());
        hashMap.put("login_im_accid", user.getImAccid());
        hashMap.put("login_im_token", user.getImToken());

        hashMap.put("login_nick_name", user.getNickName());
        hashMap.put("login_icon", user.getIcon());
        hashMap.put("login_gender", user.getGender());
        hashMap.put("login_number", user.getNumber());
        hashMap.put("login_sign", user.getSign());
        hashMap.put("login_diamond", user.getDiamond());
        //私信提醒
        hashMap.put("private_notic_status", user.getPrivateNoticStatus());
        //开播提醒
        hashMap.put("broadcast_status", user.getBroadcastStatus());
        //是否私信主播0:不能，1代表可以
        hashMap.put("is_private", user.getIsPrivate());

        //用户名片扩展字段所需要的
        hashMap.put("login_level", user.getLevel());
        hashMap.put("login_ticket", user.getTicketTotal());
        hashMap.put("login_spend", user.getSpend());

        int fans_count,follow_count;
        Fans fans;
        //我的粉丝=关注我的=(UID=我)
        fans = new Fans();
        fans.setUid(userId);
        fans_count = fansService.selectCount(fans);
        hashMap.put("login_fans_count", fans_count);
        //我的关注=我关注的=(FANS_UID=我)
        fans = new Fans();
        fans.setFansUid(userId);
        follow_count = fansService.selectCount(fans);
        hashMap.put("login_follow_count", follow_count);

        //第一次登录时用到的（获取个人信息不需要）
        hashMap.put("login_first", isFirstLogin);

        //第三方登录，特殊提示：是否绑定手机号
        hashMap.put("login_mobile_bind", StringUtil.isNotEmpty(user.getMobile()));

        HashMap map = new HashMap();
        map.put("fans_uid", userId);
        List<HashMap> followList = fansService.getList(map);
        hashMap.put("followList",followList);

        return ResultGenerator.genSuccessResult(hashMap);
    }

    @PostMapping("/login_qq")
    public Result login_qq(String openid, Integer province_id, Integer city_id, String nick_name, String gender, String figureurl, String access_token, Integer client_type)
    {
        if(StringUtil.isEmpty(openid)) {
            return ResultGenerator.genFailResult("非法参数请求");
        }

        //QQInfoBean qqInfoBean = QQAuthUtil.getWechatInfo(code,redirect_uri);
//        if(qqInfoBean == null) {
//            return ResultGenerator.genFailResult("QQ登录失败，请重试");
//        }
//        logger.info("QQInfoBean: {}", JSONObject.toJSONString(qqInfoBean));

        //第一次登录
        Boolean isFirstLogin = false;

        Long uid = 0L;

//        String wechatOpenId = qqInfoBean.getOpenid();
        QQUserInfo qqUserInfo = qqUserInfoService.findBy("openOpenid", openid);
        //logger.info("wechatUserInfo get: {}", JSONObject.toJSONString(wechatUserInfo));
        if(qqUserInfo != null) {
            uid = qqUserInfo.getUid();
        }

        Integer clientType = ClientUtil.getClientType(client_type);

//        String nick_name = qqInfoBean.getNickname();
        nick_name = UserUtil.filterName(nick_name);

        //检测用户手机号是否已注册
        User user = userService.findById(uid);
        //该手机号未注册
        if (user == null) {
            isFirstLogin = true;

            user = new User();
            user.setMobile("");
            user.setNickName(nick_name); //【来自微信】昵称
            user.setBirth("");
            user.setProvinceId(province_id);
            user.setCityId(city_id);
            user.setAccountStatus(1);
            user.setAuthenticationStatus(Constants.RZ);
            user.setClientType(Constants.CLIENT_TYPE_UNKNOWN);
            user.setCreateTime(DateUtil.getCurUnixTimeStampInt());
            if(Constants.IS_DEBUG) {
                user.setDiamond(new BigDecimal(0)); //开发调试阶段新用户默认充钻10万
            } else {
                user.setDiamond(new BigDecimal(0));
            }
            user.setDiamondRecharge(new BigDecimal(0));
            user.setIcon(figureurl);
            if("男".equals(gender))
                user.setGender(1);
            if("女".equals(gender))
                user.setGender(2);
            user.setHeight(0);
            user.setHotDesc(0);
            user.setIdCard("");
            user.setLevel(Constants.USER_LEVEL_DEF);
            user.setPayPass("");
            user.setPid(0);
            user.setUserType(Constants.USER_TYPE_AUDIENCE);
            user.setPraise(0);
            user.setProfit(new BigDecimal(0));
            user.setProfitTotal(new BigDecimal(0));
            user.setPushStatus(Constants.USER_PUSH_STATUS_DEF);
            user.setRealName("");
            user.setRecommendType(Constants.USER_RECOMMEND_TYPE_NO);
            user.setSign("");
            user.setSpend(0);
            user.setTicket(new BigDecimal(0));
            user.setTicketTotal(new BigDecimal(0));
            user.setLastLoginTime(DateUtil.getCurUnixTimeStampInt());
            user.setNumber(0L);
            user.setTotalLoginCount(0);
            user.setTotalOnlineTime(0);
            user.setToken(StringUtil.getLoginToken());
            user.setImAccid("");
            user.setImToken("");
            userService.save(user);

            //logger.info("{}", user);

            //TODO:使用事务来处理
            //保存微信信息
            qqUserInfo = new QQUserInfo();
            qqUserInfo.setAccessToken(access_token);
            qqUserInfo.setCreateTime(DateUtil.getCurUnixTimeStampInt());
            qqUserInfo.setUid(user.getId());
            qqUserInfo.setOpenOpenid(openid);
            logger.info("qqUserInfo set: {}", JSONObject.toJSONString(qqUserInfo));
            qqUserInfoService.save(qqUserInfo);

        } else {
            //TODO:检测已注册用户状态
            if(user.getAccountStatus().equals(0)) {
                return ResultGenerator.genFailResult("帐号已禁用");
            }
            //if(StringUtil.isEmpty(user.getMobile())) {
            //    return ResultGenerator.genFailResult("请绑定手机号");
            //}
        }

        //TODO:提炼成单独方法
        //如果ImAccid或ImToken为空 重新创建IM帐号
        if(StringUtil.isEmpty(user.getImAccid()) || StringUtil.isEmpty(user.getImToken())) {
            //创建网易IM帐号
            String accid = UserUtil.getImAccid();
            //扩展字段
            String props = "";
            //HashMap propsMap = new HashMap();
            //propsMap.put("uid", user.getId());
            //propsMap.put("level", Constants.USER_LEVEL_DEF);
            //props = JSON.toJSONString(propsMap);

            String resIm = NeteaseImUtil.createUser(accid, user.getNickName(), props, user.getIcon());
            try {
                JSONObject jsonObjIm = JSON.parseObject(resIm);
                Integer codeIm = jsonObjIm.getInteger("code");
                if (!codeIm.equals(200)) {
                    String errorDesc = jsonObjIm.getString("desc");
                    logger.warn("IM服务器异常({}):{}", codeIm, errorDesc);
                    return ResultGenerator.genFailResult("IM服务器异常(" + codeIm + "):" + errorDesc);
                }

                JSONObject objectIm = jsonObjIm.getJSONObject("info");

                //保存IM相关信息
                String imAccid = objectIm.getString("accid");
                //String imName = objectIm.getString("name");
                String imToken = objectIm.getString("token");

                user.setImAccid(imAccid);
                user.setImToken(imToken);

                //扩展信息 ===> 改成由客户端去更新扩展信息
                /*
                HashMap extHashMap = new HashMap();
                extHashMap.put("level", user.getLevel());
                String extJsonString = JSONUtils.toJSONString(extHashMap);
                //更新用户IM名片
                resIm = NeteaseImUtil.updateUinfo(user.getImAccid(), user.getNickName(), user.getIcon(), user.getSign(), user.getBirth(), user.getGender(), extJsonString);
                jsonObjIm = JSON.parseObject(resIm);
                codeIm = jsonObjIm.getInteger("code");
                if(!codeIm.equals(200)) {
                    String errorDesc = jsonObjIm.getString("desc");
                    return ResultGenerator.genFailResult("IM服务器异常(" + codeIm + "):" + errorDesc);
                }*/
            } catch (Exception ex) {
                logger.warn("IM服务器异常:{}", ex);
                return ResultGenerator.genFailResult("IM服务器异常:" + ex);
            }
        }

        if(user.getNumber().equals(0L)) {
            //TODO:靓号预生成-取值
            Long max=userService.getMaxNumber();
            user.setNumber(UserUtil.getNumberById(user.getId(),max));
        }
        if(StringUtil.isEmpty(user.getNickName())) {
            //设置临时昵称
            String nickName = UserUtil.getNickNameById(user.getNumber());
            user.setNickName(nickName);
        }

        //更新登录信息
        user.setLastLoginTime(DateUtil.getCurUnixTimeStampInt());
        user.setTotalLoginCount(user.getTotalLoginCount() + 1);
        user.setToken(StringUtil.getLoginToken());

        //更新客户端类型
        user.setClientType(clientType);

        //更新用户信息
        userService.update(user);

        Long userId = user.getId();

        HashMap hashMap = new HashMap();
        hashMap.put("login_uid", userId);
        hashMap.put("login_token", user.getToken());
        hashMap.put("login_im_accid", user.getImAccid());
        hashMap.put("login_im_token", user.getImToken());

        hashMap.put("login_nick_name", user.getNickName());
        hashMap.put("login_icon", user.getIcon());
        hashMap.put("login_gender", user.getGender());
        hashMap.put("login_number", user.getNumber());
        hashMap.put("login_sign", user.getSign());
        hashMap.put("login_diamond", user.getDiamond());

        //私信提醒
        hashMap.put("private_notic_status", user.getPrivateNoticStatus());
        //开播提醒
        hashMap.put("broadcast_status", user.getBroadcastStatus());
        //是否私信主播0:不能，1代表可以
        hashMap.put("is_private", user.getIsPrivate());

        //用户名片扩展字段所需要的
        hashMap.put("login_level", user.getLevel());
        hashMap.put("login_ticket", user.getTicketTotal());
        hashMap.put("login_spend", user.getSpend());

        int fans_count,follow_count;
        Fans fans;
        //我的粉丝=关注我的=(UID=我)
        fans = new Fans();
        fans.setUid(userId);
        fans_count = fansService.selectCount(fans);
        hashMap.put("login_fans_count", fans_count);
        //我的关注=我关注的=(FANS_UID=我)
        fans = new Fans();
        fans.setFansUid(userId);
        follow_count = fansService.selectCount(fans);
        hashMap.put("login_follow_count", follow_count);

        //第一次登录时用到的（获取个人信息不需要）
        hashMap.put("login_first", isFirstLogin);

        //第三方登录，特殊提示：是否绑定手机号
        hashMap.put("login_mobile_bind", StringUtil.isNotEmpty(user.getMobile()));

        HashMap map = new HashMap();
        map.put("fans_uid", userId);
        List<HashMap> followList = fansService.getList(map);
        hashMap.put("followList",followList);//我的关注



        return ResultGenerator.genSuccessResult(hashMap);
    }

    @PostMapping("/login_wechat")
    public Result login_wechat(String code, Integer province_id, Integer city_id, Integer client_type)
    {
        if(StringUtil.isEmpty(code)) {
            return ResultGenerator.genFailResult("非法参数请求");
        }

        WechatInfoBean wechatInfoBean = WechatAuthUtil.getWechatInfo(code);
        if(wechatInfoBean == null) {
            return ResultGenerator.genFailResult("微信登录失败，请重试");
        }
        logger.info("wechatInfoBean: {}", JSONObject.toJSONString(wechatInfoBean));

        //第一次登录
        Boolean isFirstLogin = false;

        Long uid = 0L;

        String wechatOpenId = wechatInfoBean.getOpenid();
        WechatUserInfo wechatUserInfo = wechatUserInfoService.findBy("wxOpenOpenid", wechatOpenId);
        //logger.info("wechatUserInfo get: {}", JSONObject.toJSONString(wechatUserInfo));
        if(wechatUserInfo != null) {
            uid = wechatUserInfo.getUid();
        }

        Integer clientType = ClientUtil.getClientType(client_type);

        String nick_name = wechatInfoBean.getNickname();
        nick_name = UserUtil.filterName(nick_name);

        //检测用户手机号是否已注册
        User user = userService.findById(uid);
        //该手机号未注册
        if (user == null) {
            isFirstLogin = true;

            user = new User();
            user.setMobile("");
            user.setNickName(nick_name); //【来自微信】昵称
            user.setBirth("");
            user.setProvinceId(province_id);
            user.setCityId(city_id);
            user.setAccountStatus(1);
            user.setAuthenticationStatus(Constants.RZ);
            user.setClientType(Constants.CLIENT_TYPE_UNKNOWN);
            user.setCreateTime(DateUtil.getCurUnixTimeStampInt());
            if(Constants.IS_DEBUG) {
                user.setDiamond(new BigDecimal(0)); //开发调试阶段新用户默认充钻10万
            } else {
                user.setDiamond(new BigDecimal(0));
            }
            user.setDiamondRecharge(new BigDecimal(0));
            user.setIcon(wechatInfoBean.getHeadimgurl()); //【来自微信】头像
            user.setGender(wechatInfoBean.getSex()); //【来自微信】性别
            user.setHeight(0);
            user.setHotDesc(0);
            user.setIdCard("");
            user.setLevel(Constants.USER_LEVEL_DEF);
            user.setPayPass("");
            user.setPid(0);
            user.setUserType(Constants.USER_TYPE_AUDIENCE);
            user.setPraise(0);
            user.setProfit(new BigDecimal(0));
            user.setProfitTotal(new BigDecimal(0));
            user.setPushStatus(Constants.USER_PUSH_STATUS_DEF);
            user.setRealName("");
            user.setRecommendType(Constants.USER_RECOMMEND_TYPE_NO);
            user.setSign("");
            user.setSpend(0);
            user.setTicket(new BigDecimal(0));
            user.setTicketTotal(new BigDecimal(0));
            user.setLastLoginTime(DateUtil.getCurUnixTimeStampInt());
            user.setNumber(0L);
            user.setTotalLoginCount(0);
            user.setTotalOnlineTime(0);
            user.setToken(StringUtil.getLoginToken());
            user.setImAccid("");
            user.setImToken("");
            userService.save(user);

            //logger.info("{}", user);

            //TODO:使用事务来处理
            //保存微信信息
            wechatUserInfo = new WechatUserInfo();
            wechatUserInfo.setAccessToken(wechatInfoBean.getAccesstoken());
            wechatUserInfo.setCreateTime(DateUtil.getCurUnixTimeStampInt());
            wechatUserInfo.setExpiresIn(wechatInfoBean.getExpiresin());
            wechatUserInfo.setRefreshToken(wechatInfoBean.getRefreshtoken());
            wechatUserInfo.setScope(wechatInfoBean.getScope());
            wechatUserInfo.setUid(user.getId());
            wechatUserInfo.setWxMpOpenid("");
            wechatUserInfo.setWxOpenOpenid(wechatInfoBean.getOpenid());
            wechatUserInfo.setWxUnionId(wechatInfoBean.getUnionid());
            logger.info("wechatUserInfo set: {}", JSONObject.toJSONString(wechatUserInfo));
            wechatUserInfoService.save(wechatUserInfo);

        } else {
            //TODO:检测已注册用户状态
            if(user.getAccountStatus().equals(0)) {
                return ResultGenerator.genFailResult("帐号已禁用");
            }
            //if(StringUtil.isEmpty(user.getMobile())) {
            //    return ResultGenerator.genFailResult("请绑定手机号");
            //}
        }

        //TODO:提炼成单独方法
        //如果ImAccid或ImToken为空 重新创建IM帐号
        if(StringUtil.isEmpty(user.getImAccid()) || StringUtil.isEmpty(user.getImToken())) {
            //创建网易IM帐号
            String accid = UserUtil.getImAccid();
            //扩展字段
            String props = "";
            //HashMap propsMap = new HashMap();
            //propsMap.put("uid", user.getId());
            //propsMap.put("level", Constants.USER_LEVEL_DEF);
            //props = JSON.toJSONString(propsMap);

            String resIm = NeteaseImUtil.createUser(accid, user.getNickName(), props, user.getIcon());
            try {
                JSONObject jsonObjIm = JSON.parseObject(resIm);
                Integer codeIm = jsonObjIm.getInteger("code");
                if (!codeIm.equals(200)) {
                    String errorDesc = jsonObjIm.getString("desc");
                    logger.warn("IM服务器异常({}):{}", codeIm, errorDesc);
                    return ResultGenerator.genFailResult("IM服务器异常(" + codeIm + "):" + errorDesc);
                }

                JSONObject objectIm = jsonObjIm.getJSONObject("info");

                //保存IM相关信息
                String imAccid = objectIm.getString("accid");
                //String imName = objectIm.getString("name");
                String imToken = objectIm.getString("token");

                user.setImAccid(imAccid);
                user.setImToken(imToken);

                //扩展信息 ===> 改成由客户端去更新扩展信息
                /*
                HashMap extHashMap = new HashMap();
                extHashMap.put("level", user.getLevel());
                String extJsonString = JSONUtils.toJSONString(extHashMap);
                //更新用户IM名片
                resIm = NeteaseImUtil.updateUinfo(user.getImAccid(), user.getNickName(), user.getIcon(), user.getSign(), user.getBirth(), user.getGender(), extJsonString);
                jsonObjIm = JSON.parseObject(resIm);
                codeIm = jsonObjIm.getInteger("code");
                if(!codeIm.equals(200)) {
                    String errorDesc = jsonObjIm.getString("desc");
                    return ResultGenerator.genFailResult("IM服务器异常(" + codeIm + "):" + errorDesc);
                }*/
            } catch (Exception ex) {
                logger.warn("IM服务器异常:{}", ex);
                return ResultGenerator.genFailResult("IM服务器异常:" + ex);
            }
        }

        if(user.getNumber().equals(0L)) {
            //TODO:靓号预生成-取值
            Long max=userService.getMaxNumber();
            user.setNumber(UserUtil.getNumberById(user.getId(),max));
        }
        if(StringUtil.isEmpty(user.getNickName())) {
            //设置临时昵称
            String nickName = UserUtil.getNickNameById(user.getNumber());
            user.setNickName(nickName);
        }

        //更新登录信息
        user.setLastLoginTime(DateUtil.getCurUnixTimeStampInt());
        user.setTotalLoginCount(user.getTotalLoginCount() + 1);
        user.setToken(StringUtil.getLoginToken());

        //更新客户端类型
        user.setClientType(clientType);

        //更新用户信息
        userService.update(user);

        Long userId = user.getId();

        HashMap hashMap = new HashMap();
        hashMap.put("login_uid", userId);
        hashMap.put("login_token", user.getToken());
        hashMap.put("login_im_accid", user.getImAccid());
        hashMap.put("login_im_token", user.getImToken());

        hashMap.put("login_nick_name", user.getNickName());
        hashMap.put("login_icon", user.getIcon());
        hashMap.put("login_gender", user.getGender());
        hashMap.put("login_number", user.getNumber());
        hashMap.put("login_sign", user.getSign());
        hashMap.put("login_diamond", user.getDiamond());
        //私信提醒
        hashMap.put("private_notic_status", user.getPrivateNoticStatus());
        //开播提醒
        hashMap.put("broadcast_status", user.getBroadcastStatus());
        //是否私信主播0:不能，1代表可以
        hashMap.put("is_private", user.getIsPrivate());

        //用户名片扩展字段所需要的
        hashMap.put("login_level", user.getLevel());
        hashMap.put("login_ticket", user.getTicketTotal());
        hashMap.put("login_spend", user.getSpend());

        int fans_count,follow_count;
        Fans fans;
        //我的粉丝=关注我的=(UID=我)
        fans = new Fans();
        fans.setUid(userId);
        fans_count = fansService.selectCount(fans);
        hashMap.put("login_fans_count", fans_count);
        //我的关注=我关注的=(FANS_UID=我)
        fans = new Fans();
        fans.setFansUid(userId);
        follow_count = fansService.selectCount(fans);
        hashMap.put("login_follow_count", follow_count);

        //第一次登录时用到的（获取个人信息不需要）
        hashMap.put("login_first", isFirstLogin);

        //第三方登录，特殊提示：是否绑定手机号
        hashMap.put("login_mobile_bind", StringUtil.isNotEmpty(user.getMobile()));
//        hashMap.put("login_mobile_bind", isFirstLogin);

        HashMap map = new HashMap();
        map.put("fans_uid", userId);
        List<HashMap> followList = fansService.getList(map);
        hashMap.put("followList",followList);

        return ResultGenerator.genSuccessResult(hashMap);
    }

    @RequestMapping("/my_info")
    public Result my_info(Long login_uid) {
        User user = userService.findById(login_uid);
        HashMap hashMap = new HashMap();
        if(user==null){
            ResultGenerator.genFailResult("用户不存在");
        }
        hashMap.put("nick_name", user.getNickName());
        hashMap.put("icon", user.getIcon());
        hashMap.put("gender", user.getGender());
        hashMap.put("number", user.getNumber());
        hashMap.put("sign", user.getSign());
        hashMap.put("diamond", user.getDiamond());
        int a=user.getLevel();
        if(a>0)
            a=a-1;
        hashMap.put("level_score_head", LevelUtil.LEVEL_SCORE.get(a));
        int b=a+1;
        if(LevelUtil.LEVEL_SCORE.size()<=b)
            b= LevelUtil.LEVEL_SCORE.size()-1;
        hashMap.put("level_score_tail", LevelUtil.LEVEL_SCORE.get(b));

        //私信提醒
        hashMap.put("private_notic_status", user.getPrivateNoticStatus());
        //开播提醒
        hashMap.put("broadcast_status", user.getBroadcastStatus());
        //是否私信主播0:不能，1代表可以
        hashMap.put("is_private", user.getIsPrivate());

        //用户名片扩展字段所需要的
        hashMap.put("level", user.getLevel());
        hashMap.put("ticket", user.getTicket().intValue());
        hashMap.put("ticket_total", user.getTicketTotal().intValue());

        hashMap.put("spend", user.getSpend());
         //
        hashMap.put("in_family", user.getSpend());

        int fans_count,follow_count;
        Fans fans;
        //我的粉丝=关注我的=(UID=我)
        fans = new Fans();
        fans.setUid(login_uid);
        fans_count = fansService.selectCount(fans);
        hashMap.put("fans_count", fans_count);
        //我的关注=我关注的=(FANS_UID=我)
        fans = new Fans();
        fans.setFansUid(login_uid);
        follow_count = fansService.selectCount(fans);
        hashMap.put("follow_count", follow_count);

        //修改个人信息需要的参数（登录时不需要）
        hashMap.put("authentication_status", user.getAuthenticationStatus());
        hashMap.put("province_id", user.getProvinceId());
        hashMap.put("city_id", user.getCityId());
        hashMap.put("birth", user.getBirth());
        hashMap.put("height", user.getHeight());
        hashMap.put("age", DateUtil.getAgeByBirth(user.getBirth()));
        hashMap.put("score_user", user.getScoreUser());

        //第三方登录，特殊提示：是否绑定手机号
        hashMap.put("mobile_bind", StringUtil.isNotEmpty(user.getMobile()));
        HashMap map = new HashMap();
        map.put("fans_uid", login_uid);
        List<HashMap> followList = fansService.getList(map);
        hashMap.put("followList",followList);

        //获取用户+v信息
        HashMap uservMap = userVService.getMyVInfo(login_uid);
        if(uservMap != null && uservMap.size() > 0) {
            hashMap.put("v_des", uservMap.get("v_des")); //+v描述信息
            hashMap.put("v_img_url", uservMap.get("v_img_url")); //+v图片地址
        }

        ////获取is 家族?信息
        HashMap userjz = userService.getJzInfo(login_uid);
        Long familyId=(Long) userjz.get("familyId");
        if (familyId==0){
            hashMap.put("jzStatus",-1); //未提交
        }else{
            Integer jzStatus=(Integer) userjz.get("jzStatus");
            if (jzStatus==0){
                hashMap.put("jzStatus",0); //审核中
            }else if(jzStatus==1){
                hashMap.put("jzStatus",1); //审核pass
                hashMap.put("familyId",familyId); //审核pass
            }else if (jzStatus==2){
                hashMap.put("jzStatus",2); //审核no pass
            }else if (jzStatus==null){
                hashMap.put("familyId",familyId); //家族长id
            }else{
                hashMap.put("jzStatus",-1); //未提交
             }
        }
        return ResultGenerator.genSuccessResult(hashMap);
    }
    @RequestMapping("/other_info")
    public Result other_info(Long uid) {
        User user = userService.findById(uid);
        HashMap hashMap = new HashMap();
        if(user==null){
            ResultGenerator.genFailResult("用户不存在");
        }
        hashMap.put("nick_name", user.getNickName());
        hashMap.put("icon", user.getIcon());
        hashMap.put("gender", user.getGender());
        hashMap.put("number", user.getNumber());
        hashMap.put("sign", user.getSign());
        hashMap.put("spend", user.getSpend());
        hashMap.put("ticket_total", user.getTicketTotal().intValue());

        int fans_count,follow_count;
        Fans fans;
        //我的粉丝=关注我的=(UID=我)
        fans = new Fans();
        fans.setUid(uid);
        fans_count = fansService.selectCount(fans);
        hashMap.put("fans_count", fans_count);
        //我的关注=我关注的=(FANS_UID=我)
        fans = new Fans();
        fans.setFansUid(uid);
        follow_count = fansService.selectCount(fans);
        hashMap.put("follow_count", follow_count);
        hashMap.put("province_id", user.getProvinceId());
        hashMap.put("city_id", user.getCityId());
        hashMap.put("birth", user.getBirth());
        hashMap.put("height", user.getHeight());
        hashMap.put("age", DateUtil.getAgeByBirth(user.getBirth()));
        hashMap.put("level", user.getLevel());

        return ResultGenerator.genSuccessResult(hashMap);
    }
    @PostMapping("/mobile_bind_status")
    public Result mobile_bind_status(Long login_uid) {
        User user = userService.findById(login_uid);
        int mobile_bind_status = StringUtil.isNotEmpty(user.getMobile()) ? Constants.SUCCESS : Constants.FAILED;

        HashMap hashMap = new HashMap();
        hashMap.put("status", mobile_bind_status);
        return ResultGenerator.genSuccessResult(hashMap);
    }

    @PostMapping("/mobile_bind")
    public Result mobile_bind(Long login_uid, String mobile, String sms_code) {
        //检测短信验证码
        Result checkSmsCodeResult = checkSmsCode(mobile, sms_code);
        if (checkSmsCodeResult.getCode() != 200) {
            return checkSmsCodeResult;
        }
        User user = userService.findBy("mobile",mobile);
        if(user!=null){
            return ResultGenerator.genFailResult("手机号已被使用");
        }
         user = userService.findById(login_uid);

        boolean isBind = StringUtil.isNotEmpty(user.getMobile());
        if (isBind) {
            return ResultGenerator.genFailResult("不能重复绑定");
        }

        user.setMobile(mobile);
        userService.update(user);

        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/authentication_status")
    public Result Authentication(Long login_uid) {

        HashMap hashMap = new HashMap();
        if(!DateUtil.allowLiveBroadcast())
            hashMap.put("isSeeding", 1); //不允许开播
        else
            hashMap.put("isSeeding", 0); //允许开播

        UserAuthentication userAuthentication = userAuthenticationService.findBy("uid", login_uid);
        if(userAuthentication == null) {
            hashMap.put("status", -2); //未提交认证
            hashMap.put("admin_time", 0);
            hashMap.put("refuse_reason", "");
        } else {
            hashMap.put("status", userAuthentication.getStatus());
            hashMap.put("admin_time", userAuthentication.getAdminTime());
            hashMap.put("refuse_reason", userAuthentication.getRefuseReason());
        }
        return ResultGenerator.genSuccessResult(hashMap);
    }

    //TODO:认证通过后更新生日、省市、性别
    @PostMapping("/authentication")
    public Result Authentication(Long login_uid, String real_name, String gender, Integer age, String mobile, String sms_code, String id_card, String pic_id_front, String pic_id_back) {
        User user1 = userService.findById(login_uid);
        if (user1 == null) {
            return ResultGenerator.genFailResult("用户不存在");
        }
        if(StringUtil.isEmpty(mobile) || StringUtil.isEmpty(sms_code)) {
            return ResultGenerator.genFailResult("手机号和验证码均不能为空");
        }
        //检测短信验证码
        Result checkSmsCodeResult = checkSmsCode(mobile, sms_code);
        if (checkSmsCodeResult.getCode() != 200) {
            return checkSmsCodeResult;
        }

        if(!IdCardUtil.isValidatedIdcard(id_card)) {
            return ResultGenerator.genFailResult("错误的身份证号码");
        }
        if(StringUtil.isEmpty(real_name) || StringUtil.isEmpty(pic_id_front) || StringUtil.isEmpty(pic_id_back)) {
            return ResultGenerator.genFailResult("必要参数不能为空");
        }
        UserAuthentication userAuthentication1 = userAuthenticationService.findBy("idCard", id_card);
        if(userAuthentication1!=null){
            return ResultGenerator.genFailResult("该身份证已被认证");
        }
        UserAuthentication userAuthentication = userAuthenticationService.findBy("uid", login_uid);

        if (userAuthentication == null) {//未提交认证

            userAuthentication = new UserAuthentication();
            userAuthentication.setUid(login_uid);
            if("男".equals(gender))
                userAuthentication.setGender(1);
            if("女".equals(gender))
                userAuthentication.setGender(2);
            userAuthentication.setAge(age);

            userAuthentication.setIdCard(id_card);
            userAuthentication.setRealName(real_name);
            userAuthentication.setPicIdFront(pic_id_front);
            userAuthentication.setPicIdBack(pic_id_back);
            userAuthentication.setMobile(mobile);

            userAuthentication.setCreateTime(DateUtil.getCurUnixTimeStampInt());
            userAuthentication.setAdminTime(0);
            userAuthentication.setAdminUid(0);
            userAuthentication.setStatus(0);//未处理
            userAuthentication.setUpdateTime(0);
            userAuthentication.setRefuseReason("");
            int count = userAuthenticationService.save(userAuthentication);
            if (count == 0) {
                return ResultGenerator.genFailResult("提交认证信息失败");
            }

            User user = userService.findById(login_uid);
            user.setAuthenticationStatus(1);//认证状态【0=未认证/1=申请认证/2=认证通过】
            //user.setRealName(real_name);
            //user.setIdCard(id_card);
            count = userService.update(user);
            if (count == 0) {
                return ResultGenerator.genFailResult("提交认证信息失败~");
            }
        } else { //已提交过认证
            switch (userAuthentication.getStatus()) {
                case 1: //认证已通过
                    return ResultGenerator.genFailResult("认证已通过，无需再次提交申请~");
                case 0: //认证未处理
                    return ResultGenerator.genFailResult("已提交过认证申请，请耐心等待处理~");
                default: //认证未通过
                    userAuthentication.setIdCard(id_card);
                    userAuthentication.setRealName(real_name);
                    if("男".equals(gender))
                        userAuthentication.setGender(1);
                    if("女".equals(gender))
                        userAuthentication.setGender(2);
                    userAuthentication.setAge(age);
                    userAuthentication.setPicIdFront(pic_id_front);
                    userAuthentication.setPicIdBack(pic_id_back);
                    userAuthentication.setMobile(mobile);

                    userAuthentication.setStatus(0);
                    userAuthentication.setUpdateTime(DateUtil.getCurUnixTimeStampInt());
                    userAuthentication.setRefuseReason("");
                    int count = userAuthenticationService.update(userAuthentication);
                    if (count == 0) {
                        return ResultGenerator.genFailResult("重新提交认证信息失败");
                    }
            }
        }

        return ResultGenerator.genSuccessResult("认证资料提交成功");
    }

    @PostMapping("/info_update")
    public Result info_update(HttpServletRequest request){
        Long login_uid = StringUtil.getLong(request.getParameter("login_uid"));
        //logger.info("{}", login_uid);
        User user = userService.findById(login_uid);

        //是否修改
        Boolean isChange = false;

        String nick_name = request.getParameter("nick_name");

        //敏感词过滤
        SensitivewordFilter filter = new SensitivewordFilter();
        if(nick_name!=null) {
            Set<String> set = filter.getSensitiveWord(nick_name, 1);
            if (set.size() > 0)
                return ResultGenerator.genFailResult("此昵称涉及敏感词汇，无法创建！");

            nick_name = UserUtil.filterName(nick_name);
        }

        //昵称判重
        String nickName = user.getNickName();
        if(StringUtil.isNotEmpty(nick_name)) {
            if(nickName.equals(nick_name))
                return ResultGenerator.genFailResult("此昵称已被使用，请重新输入！");
        }


        if(StringUtil.isNotEmpty(nick_name)) {
            isChange = true;
            user.setNickName(nick_name);
        }

        String birth = request.getParameter("birth");
        if(StringUtil.isNotEmpty(birth)) {
            if (ValidateUtil.isDate(birth)) {
                isChange = true;
                user.setBirth(birth);
            } else {
                return  ResultGenerator.genFailResult("错误的生日格式");
            }
        }

        Integer height = StringUtil.getInt(request.getParameter("height"));
        if(!height.equals(0)) {
            isChange = true;
            user.setHeight(height);
        }

        Integer gender = StringUtil.getInt(request.getParameter("gender"));
        if(gender.equals(1) ||  gender.equals(2)) {
            isChange = true;
            user.setGender(gender);
        }

        String signature = request.getParameter("signature");
        if(StringUtil.isNotEmpty(signature)) {
            isChange = true;
            user.setSign(signature);
        }

        Integer province_id = StringUtil.getInt(request.getParameter("province_id"));
        Integer city_id = StringUtil.getInt(request.getParameter("city_id"));
        if(!province_id.equals(0) && !city_id.equals(0)) {
            isChange = true;
            user.setProvinceId(province_id);
            user.setCityId(city_id);
        }

        String icon = request.getParameter("icon");
        //icon = icon.replace(Constants.STATIC_URL_UPLOAD, "");
        if(StringUtil.isNotEmpty(icon)) {
            isChange = true;
            user.setIcon(icon);
        }

        if(isChange.equals(false)) { //未提交修改
            return  ResultGenerator.genFailResult("未提交必要的资料");
        }

        userService.update(user);
        return  ResultGenerator.genSuccessResult();
    }

    @PostMapping("/search")
    public Result search(String keyword, Integer page, Integer page_size) {
        if(StringUtil.isEmpty(keyword)) {
            return  ResultGenerator.genFailResult("关键词不能为空");
        }

        PageUtil.startPage(page, page_size);
        Map<String, Object> map = new HashMap();
        map.put("keyword", keyword);
        List<HashMap> userList= userService.getList(map);

        HashMap roomListHashMap = PageUtil.getPageInfoHashMap(new PageInfo(userList));

        return ResultGenerator.genSuccessResult(roomListHashMap);
    }

    @PostMapping("/local_tyrant_rank_list") //榜单-土豪榜
    public Result local_tyrant_rank_list(Integer page, Integer page_size) {
        PageUtil.startPage(page, page_size);
        List<HashMap> localTyrantRankList = userService.getLocalTyrantRankList();
        HashMap localTyrantRankListHashMap = PageUtil.getPageInfoHashMap(new PageInfo(localTyrantRankList));

        return ResultGenerator.genSuccessResult(localTyrantRankListHashMap);
    }
    @PostMapping("/log")
    public Result log(Long login_uid, Integer type) {
        if (type == 2) {
            UserLog userLog = new UserLog();
            userLog.setType(2);
            userLog.setUid(login_uid);
            userLog.setUuid(0);
            userLog.setCreateTime(DateUtil.getCurUnixTimeStampInt());
            userLogService.save(userLog);
            //score
            long times = userLogService.getTime(String.valueOf(login_uid));
            if(times<4){
                //每次分享加10经验
                User user = userService.findById(login_uid);
                user.setScoreUser(user.getScoreUser()+10);
                int level= LevelUtil.getLevel(user.getScoreUser());
                user.setLevel(level);
                userService.update(user);

            }
            HashMap map=new HashMap();
            map.put("times",times );
            return ResultGenerator.genSuccessResult(map);

        }else if(type==3){
            //登陆加20经验
//            Jedis client = jedisPool.getResource();
//            long times=client.hincrBy(String.valueOf(login_uid),"login",1);
//            logger.debug("");
//            client.close();
//            if(times==1){
//                User user = userService.findById(login_uid);
//                user.setScoreUser(user.getScoreUser()+20);
//                int level=LevelUtil.getLevel(user.getScoreUser());
//                user.setLevel(level);
//                userService.update(user);
//
//            }
            HashMap map=new HashMap();
            map.put("times",0 );
            return ResultGenerator.genSuccessResult(map);
        }

        return ResultGenerator.genSuccessResult();
    }





    @PostMapping("/withdrawals") //提现
    public Result withdrawals(HttpServletRequest request) {
        Long login_uid = StringUtil.getLong(request.getParameter("login_uid"));
        User user = userService.findById(login_uid);
        BigDecimal userTicket = user.getTicket();
        HashMap hashMap = new HashMap();
        hashMap.put("ticket", userTicket);
        HashMap map;
        BigDecimal percentage = CalculateUtil.getSubtractBalance(new BigDecimal(1),new BigDecimal(Constants.COMMISSION_CHARGE));

        String message;

        WithdrawalsLog withdrawalsLog = new WithdrawalsLog();
        String ticket = request.getParameter("ticket");
        int x=0;
        try{
            x=Integer.parseInt(ticket);
            if(x%100!=0){
                return ResultGenerator.genFailResult("非法数字");
            }

        }   catch (Exception e){
            logger.error(e.getStackTrace().toString());
            return ResultGenerator.genFailResult("非法数字");
        }

        BigDecimal ticket1=new BigDecimal(x);
        BigDecimal ticket2=new BigDecimal(x*percentage.doubleValue());
        if(userTicket.intValue()< x) {
            return ResultGenerator.genFailResult("票不足", hashMap);
        }
        //每次不低于50元
        if (ticket2.intValue()/10<50){
            return ResultGenerator.genFailResult("提现低于50元", hashMap);
        }
        //每月累计50万
        BigDecimal total=withdrawalsLogService.getTotalMoneyOneMonth(login_uid);
        if(total!=null) {
            if ((total.intValue()+ticket2.intValue()) * 10 > 500_000) {
                return ResultGenerator.genFailResult("提现累计超过50万", hashMap);
            }
        }
        message = "提现申请成功";
        //扣票
        map = new HashMap();
        map.put("change", ticket1);
        map.put("uid", login_uid);
        userService.setTic(map);
        withdrawalsLog.setChanges(ticket1);
        withdrawalsLog.setSurplus(ticket2);

        user = userService.findById(login_uid);
        BigDecimal d_balance = user.getDiamond();
        BigDecimal t_balance = user.getTicket();
        hashMap.put("diamond", d_balance);
        hashMap.put("ticket", t_balance);

        //向提现表添加记录
        String name = request.getParameter("name");
        String bank_name = request.getParameter("bank_name");
        String bank_card_num = request.getParameter("bank_card_num");
        String remark = request.getParameter("remark");

        withdrawalsLog.setUid(login_uid);

        withdrawalsLog.setBalance(t_balance);
        withdrawalsLog.setName(name);
        withdrawalsLog.setBankName(bank_name);
        withdrawalsLog.setBankCardNum(bank_card_num);
        withdrawalsLog.setRemark(remark);
        withdrawalsLog.setCreateTime(DateUtil.getCurUnixTimeStampInt());
        withdrawalsLog.setStatus(0);
        withdrawalsLogService.save(withdrawalsLog);
        user = userService.findById(login_uid);
        hashMap.put("ticket", user.getTicket().intValue());

        return ResultGenerator.genSuccessResult(message, hashMap);
    }


}
